<template>
	<div>
		<div class="search">
			<el-row>
				<el-col :span="18">
					<el-date-picker
						size="mini"
						v-model="date"
						value-format="yyyy-MM-dd"
						type="daterange"
						range-separator="至"
						start-placeholder="开始日期"
						end-placeholder="结束日期">
					</el-date-picker>
					<el-button size="mini" @click="handleSearch" class="btn" type="primary">查询</el-button>
				</el-col>
				<el-col :span="6" class="align-right">
					<el-radio-group v-model="type" size="mini" @change="handleChange">
						<el-radio-button label="day">按日</el-radio-button>
						<el-radio-button label="hour">按时</el-radio-button>
					</el-radio-group>
				</el-col>
			</el-row>
		</div>
		<div class="event-chart" v-loading="loading"></div>
		<el-table
			v-loading="loading"
			size="mini"
			border
			lazy
			row-key="id"
			:data="tableData">
			<el-table-column
				v-for="item in columns"
				:key="item.prop"
				:prop="item.prop"
				:label="item.label"
				:min-width="item.width"
				:sortable="item.sortable"
				:show-overflow-tooltip="true">
				<template slot-scope="scope">
					<span>{{(scope.row[item.prop] || Number(scope.row[item.prop]) == 0) ? scope.row[item.prop] : "--"}}</span>
				</template>
			</el-table-column>
		</el-table>
	</div>
</template>

<script>
	export default {
		name: "eventStatistic",
		data() {
			return {
				loading: false,
				date: "",
				type: "day",
				chartStatus: false,
				columns: [
					{
						prop: "visitTime",
						label: "日期"
					},
					{
						prop: "hitCount",
						label: "事件浏览量"
					},
					{
						prop: "userCount",
						label: "事件用户量"
					},
					{
						prop: "avgUserHitCount",
						label: "户均点击量"
					},
				],
				tableData: [],
				chartType: null
			}
		},
		props: ["info"],
		watch: {
			info: {
				handler(val) {
					this.chartType = val.type;

					// 初始化
					this.handleChart([]);
					this.handleColumns([]);
					this.handleInitDate();
				},
				immediate: true
			},
			// pageId: {
			// 	handler() {
			// 		this.chartType = "page";
			// 		this.handleInitDate();
			// 	},
			// 	immediate: true
			// },
		},
		mounted() {
			// this.handleInitDate();
		},
		methods: {
			handleInitDate() {
				let endDate = this.$moment().format("YYYY-MM-DD");
				let startDate = this.$moment().subtract(7, 'days').format("YYYY-MM-DD");
				this.date = [startDate, endDate];
				this.handleQueryEventReport();
			},
			handleChange() {
				this.handleQueryEventReport();
			},
			// 搜索
			handleSearch() {
				this.handleQueryEventReport();
			},
			// 查询事件统计
			async handleQueryEventReport() {
				let startTime = "", endTime = "";
				console.log(this.date, "this.date");
				if (this.date) {
					startTime = this.date[0];
					endTime = this.date[1];
				}
				let data = {
					timeUnit: this.type,
					startTime,
					endTime
				};
				if (this.chartType === 'page') {
					data.pageId = this.info.id;
				}
				if (this.chartType === 'track') {
					data.trackId = this.info.id;
				}
        // 测试数据
        /*let res = {
            value: {
                list: [
                    {
                        "avgUserHitCount":1.05,
                        "eventId":"testEventID",
                        "hitCount":0,
                        "timeUnit":"day",
                        "trackId":"testTrackId",
                        "userCount":0,
                        "visitTime":"2021-05-12 00:00:00"
                    },
                    {
                        "avgUserHitCount":1.05,
                        "eventId":"testEventID",
                        "hitCount":"2006.0",
                        "timeUnit":"day",
                        "trackId":"testTrackId",
                        "userCount":"1908.0",
                        "visitTime":"2021-05-13 00:00:00"
                    },
                    {
                        "avgUserHitCount":1.05,
                        "eventId":"testEventID",
                        "hitCount":"1952.0",
                        "timeUnit":"day",
                        "trackId":"testTrackId",
                        "userCount":"1867.0",
                        "visitTime":"2021-05-14 00:00:00"
                    }
                ]
            }
        }*/
				this.loading = true;
				let res = await this.$eventApi.eventReport(data);
				try {
					let chartDom = document.querySelector(".event-chart");
					console.log(chartDom);
					if (res) {
						let {list} = res.value;
						if (this.type === "day") {
							list = list.map(item => {
								let str = item.avgUserHitCount.toString();
								let strArr = str.split(".");
								if (strArr.length > 1) {
									item.avgUserHitCount = Number(item.avgUserHitCount.toFixed(2));
								}
								item.visitTime = item.visitTime.slice(0, 10);
								return item;
							})
						}
						this.handleChart(list);
						this.handleColumns(list);
					}
					this.loading = false;
				} catch (err) {
					this.loading = false;
				}


			},
			handleColumns(list) {
				this.tableData = list;
				/*let data = [];
        let columns = [
            {
                prop: "type",
                label: "类型",
                width: 100
            },
        ];
        dataRows.forEach((item) => {
            let obj = {
                prop: item,
                label: item,
                width: 120
            };
            columns.push(obj);
        });
        values.forEach((item, i) => {
            let obj = {
                type: typeValues[i]
            };
            dataRows.forEach((date, j) => {
                obj[date] = item[j];
            });
            data.push(obj);
        });
        this.columns = columns;
        this.tableData = data;*/
			},
			// chart图表
			handleChart(list) {
				/*let {dataRows, values} = res.value;*/
				let dataRows = [];
				let avgUserHitCountArr = [], hitCountArr = [], userCountArr = [];
				list.forEach(item => {
					dataRows.push(item.visitTime);
					avgUserHitCountArr.push(item.avgUserHitCount);
					hitCountArr.push(item.hitCount);
					userCountArr.push(item.userCount);
				});
				console.log(avgUserHitCountArr, "avgUserHitCountArr");
				console.log(hitCountArr, "hitCountArr");
				console.log(userCountArr, "userCountArr");
				console.log(dataRows, "dataRows");

				this.$nextTick(() => {
					let chartDom = document.querySelector(".event-chart");
					if (chartDom) {
						let myChart;
						if (myChart !== null && myChart !== "" && myChart !== undefined) {
							myChart.dispose();
						}
						myChart = this.$echarts.init(chartDom);
						let option;

						option = {
							grid: {
								left: '3%',
								right: '4%',
								bottom: '3%',
								containLabel: true
							},
							legend: {
								data: ["事件浏览量", "事件用户量", "户均点击量"]
							},
							dataZoom: [
								{
									type: 'slider',
									start: 0,
									end: 100
								},
								{
									start: 0,
									end: 100
								}
							],
							xAxis: {
								type: 'category',
								// data: ['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05', '2021-01-06', '2021-01-07']
								data: dataRows
							},
							yAxis: {
								type: 'value'
							},
							series: [
								{
									name: '事件浏览量',
									type: 'line',
									smooth: true,
									// data: [150, 232, 201, 154, 190, 330, 410]
									data: hitCountArr
								},
								{
									name: '事件用户量',
									type: 'line',
									smooth: true,
									// data: [320, 332, 301, 334, 390, 330, 320]
									data: userCountArr
								},
								{
									name: '户均点击量',
									type: 'line',
									smooth: true,
									// data: [820, 932, 901, 934, 1290, 1330, 1320]
									data: avgUserHitCountArr
								},
							]
						};

						option && myChart.setOption(option, true);
						console.log(myChart);
					}
				})

			},
		}
	}
</script>

<style scoped lang="scss">
	.search {
		.btn {
			margin-left: 10px;
		}
	}

	.event-chart {
		margin: 15px 0;
		width: 100%;
		height: 300px;
	}
</style>

